package logic

import (
	"context"
	"meituan-waimai/models/mysql"

	"meituan-waimai/meituanrpc/internal/svc"
	"meituan-waimai/meituanrpc/meituanrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type MerchantListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewMerchantListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MerchantListLogic {
	return &MerchantListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *MerchantListLogic) MerchantList(in *meituanrpc.MerchantListRequest) (*meituanrpc.MerchantListResponse, error) {
	// todo: add your logic here and delete this line
	var merchant []mysql.Merchant
	query := mysql.DB.Model(&mysql.Merchant{})
	// 支持按品类、配送费、起送价、优惠活动等多条件组合查询
	if in.Category != "" { //品类筛选
		query = query.Where("category = ?", in.Category)
	}
	if in.DeliveryFee != "" { //配送费筛选
		query = query.Where("delivery_fee <= ?", in.DeliveryFee)
	}
	if in.StartingPrice != "" { //起步价筛选
		query = query.Where("starting_price <= ?", in.StartingPrice)
	}
	if in.DiscountedActivities != "" { //优惠活动筛选
		query = query.Where("discounted_activities = ?", in.DiscountedActivities)
	}

	//支持按评分、销量、距离等多维度排序，默认展示营业状态为"在线"的优质商家
	if in.Score == "true" { //评分排序，true为降序
		query = query.Order("score desc")
	} else if in.Score == "false" { //false为升序
		query = query.Order("score asc")
	}
	if in.SalesVolume == "true" { //销量排序，true为降序
		query = query.Order("sales_volume desc")
	} else if in.SalesVolume == "false" { //false为升序
		query = query.Order("sales_volume asc")
	}
	if in.Distance == "true" { //距离排序，true为降序
		query = query.Order("distance desc")
	} else if in.Distance == "false" { //false为升序
		query = query.Order("distance asc")
	}
	// 默认展示营业状态为在线的优质商家
	query = query.Where("business_status = 1").Find(&merchant) // 0-停业，1-营业

	var list []*meituanrpc.MerchantList
	for _, m := range merchant {
		slice := meituanrpc.MerchantList{
			MerchantId:           int64(m.ID),
			MerchantName:         m.MerchantName,
			Score:                int64(m.Score),
			SalesVolume:          m.SalesVolume,
			Distance:             float32(m.Distance),
			Category:             m.Category,
			DeliveryFee:          float32(m.DeliveryFee),
			StartingPrice:        float32(m.StartingPrice),
			DiscountedActivities: m.DiscountedActivities,
			BusinessStatus:       int64(m.BusinessStatus),
		}
		list = append(list, &slice)
	}
	return &meituanrpc.MerchantListResponse{
		List: list,
	}, nil
}
